package com.boarsoft.boar.sys.biz;

import java.util.Date;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.boarsoft.boar.sys.SysVerifyBiz;
import com.boarsoft.boar.sys.entity.SysVerify;
import com.boarsoft.common.Util;
import com.boarsoft.common.util.DateUtil;
import com.boarsoft.hibernate.biz.SimpleBizImpl;

@Component("baseVerifyBiz")
public class SysVerifyBizImpl extends SimpleBizImpl implements SysVerifyBiz {
	public final static int ACCOUNT_VERIFY_VALIDITY = 30;// 账号验证码有效期，单位天

	@Override
	@Transactional
	public void save(SysVerify o) {
		SysVerify a = (SysVerify) dao.find(SysVerify.class,
				String.format("and (email='%s' or phone='%s')", o.getEmail(), o.getPhone()));
		String ed = Util.date2str(DateUtil.addDay(new Date(), ACCOUNT_VERIFY_VALIDITY), Util.STDDTF);
		if (a == null) {
			if (Util.strIsEmpty(o.getTime()))
				o.setTime(ed);
			dao.save(o);
		} else {
			a.setTime(ed);
			a.setCode(o.getCode());
			dao.update(a);
		}
	}

	@Override
	@Transactional(readOnly = true)
	public SysVerify find(String uc) {
		StringBuilder sb = new StringBuilder();
		sb.append("and time>'").append(Util.getStdfDateTime()).append("'");
		if (uc.contains("@")) {
			sb.append(" and email='").append(uc).append("'");
		} else {
			sb.append(" and phone='").append(uc).append("'");
		}
		return (SysVerify) dao.find(SysVerify.class, sb.toString());
	}

	@Override
	@Transactional(readOnly = true)
	public SysVerify check(String uc, String vc) {
		StringBuilder sb = new StringBuilder();
		if (uc.contains("@")) {
			sb.append("and email='").append(uc).append("'");
		} else {
			sb.append("and phone='").append(uc).append("'");
		}
		sb.append(" and code='").append(vc).append("'");
		// 有效期30天
		String d = Util.date2str(DateUtil.addDay(new Date(), ACCOUNT_VERIFY_VALIDITY), Util.STDDTF);
		sb.append(" and time<'").append(d).append("'");
		return (SysVerify) dao.find(SysVerify.class, sb.toString());
	}

	@Override
	@Transactional
	public void delete(SysVerify o) {
		dao.delete(o);
	}
}